<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->helper(array('form', 'url'));
		$this->load->config('adsense', TRUE);
		$this->load->library('adgeek_view');
		$this->load->library('form_validation');
		$this->load->library('security');
		$this->load->library('session');
		$this->load->library('soapclientnusoap');
		$this->load->library('google-api-php-client/AdSenseHostAuth');
		$this->load->model('publisher');
		define('LIB_DOC_ROOT', $_SERVER['DOCUMENT_ROOT'].'/application/libraries/google-api-php-client/');
		$this->session_id = $this->session->userdata('session_id');
		
	}

	function index()
	{	
		$this->load->view('adsense/register_how', '');
	}
	
	function whatisadsense()
	{	
		$this->load->view('adsense/whatisadsense', '');
	}
	
	function authtocallback(){
		$data = $this->input->get(NULL, TRUE);
		if(isset($data['error']) && $data['error'] == 'access_denied'){
			redirect('account/create_failed');	
		}
		
		$this->adsensehostauth->authenticate('adgeek',$data['code']);
		redirect('account/register_form');
	}
	
	function register_success(){
		$data = $this->input->get(NULL, TRUE);
		
		if(isset($data['token'])){
			$this->verify_token($data['token']);
		}
		elseif(isset($data['error'])){
			redirect(''); //access denied
		}
		elseif(isset($data['code'])){
			redirect('account/register_form');
		}
		else{
			$this->session->unset_userdata('user_data');
			$this->load->view('adsense/register_success', '');	
		}
	}
	
	function register_auth(){
		
		//echo $this->session_id;exit;
		if($this->adsensehostauth->authenticate('adgeek') == NULL){
			redirect('account/register_form');
		}
	}
	
	function create_failed(){
		$this->load->view('adsense/create_failed', '');
	}
	
	function register_form($adseneValidationErrorCode=''){
		$this->adsensehostauth->authenticate('adgeek');
		$user_data = $this->session->userdata('user_data');
		if(!empty($adseneValidationErrorCode)){
			$user_data['adseneValidationErrorCode'] = $adseneValidationErrorCode;
		}
		$this->load->view('adsense/register_form', $user_data);
	}
	
	function register_form_confirm(){
		$this->adsensehostauth->authenticate('adgeek');
		//echo "<pre>";print_r($user_data = $this->session->userdata('user_data'));echo "</pre>";
		$user_data = $this->session->userdata('user_data');
		$this->load->view('adsense/register_form_confirm', $user_data);
	}
	
	function create_validation()
	{
		//echo "<pre>";print_r($this->input->post(NULL, TRUE));echo "</pre>";exit;
		$this->adsensehostauth->authenticate('adgeek');
		$this->form_validation->set_rules('usersPreferredLocale', 'Users Preferred Locale', 'trim|required|xss_clean');
		$this->form_validation->set_rules('websiteUrl', 'Website URL', 'trim|required|xss_clean');
		$this->form_validation->set_rules('websiteLocale', 'Website Locale', 'trim|required|xss_clean');
		$this->form_validation->set_rules('productCode', 'Product code', 'trim|required|xss_clean');
		$this->form_validation->set_rules('adsenseGuidelineRule1', 'Account Exist', 'trim|xss_clean');
		$this->form_validation->set_rules('adsenseGuidelineRule2', 'Account Exist', 'trim|xss_clean');
		
		if($this->form_validation->run()){
			$this->session->set_userdata('user_data',$this->input->post(NULL, TRUE));
			redirect('account/register_form_confirm');	
		}
		else{
			$this->load->view('adsense/register_form', '');
		}
	}
	
	function get_all_ad_clients_for_host(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth->authenticate($this->session_id);
			  
			  	$action = 'GetAllAdClientsForHost';
			    
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
				
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $result = $example->render();
				
			    printHtmlFooter();
				$this->adsensehostauth->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function get_all_ad_clients_for_publisher($publisher_account_id=''){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth->authenticate('adgeek');
			  
			  	$action = 'GetAllAdClientsForPublisher';
			    //$publisher_account_id = 'pub-3473562081766876';
			    //7606605853518273 lilindead
			    //3473562081766876 ryanhu@clicking
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $result = $example->render($publisher_account_id);
				echo "<pre>";print_r($result);echo "</pre>";
				$adClients = $result['items'];
				$content = array();
		       if (isset($adClients)) {
		         foreach ($adClients as $adClient) {
				   $content[$adClient['productCode']] = $adClient['id'];
		        }
			   }
				$content['accountId'] = $publisher_account_id;
				$this->adsensehostauth->refreshToken();
				return $content;
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function add_ad_unit_to_publisher(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  $publisher_id = array(
			  'publisher_account_id' => 'pub-7606605853518273',
			  'publisher_ad_account_id' => 'ca-pub-7606605853518273'
			  );
			  $this->adsensehostauth->authenticate($this->session_id);
			  
			  	$action = 'AddAdUnitToPublisher';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $result = $example->render($publisher_id);
			    printHtmlFooter();
				$this->adsensehostauth->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	

	function get_all_custom_channel_for_host(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
				$data = array();
			  $data['ad_host_client_id'] = $this->config->item('developer_client_host_id', 'adsense');
			  $data['max_page_size'] = 1000;
			  $this->adsensehostauth->authenticate($this->session_id);
			  
			  	$action = 'GetAllCustomChannelsForHost';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $result = $example->render($data);
				$this->adsensehostauth->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function get_all_ad_units_for_publisher(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  $publisher_id = array(
			  'publisher_account_id' => 'pub-3473562081766876',
			  'publisher_ad_account_id' => 'ca-pub-3473562081766876',
			  'max_page_size'			=> 1000
			  );
			  $this->adsensehostauth->authenticate($this->session_id);
			  
			  	$action = 'GetAllAdUnitsForPublisher';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $result = $example->render($publisher_id);
			    printHtmlFooter();
				$this->adsensehostauth->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function get_account_data_for_existing_publisher(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  $publisher_id = array(
				  0=>array('accountId'=>'pub-3473562081766876'),
				  1=>array('accountId'=>'pub-7606605853518273')
			  );
			  $this->adsensehostauth->authenticate($this->session_id);
			  
			  	$action = 'GetAccountDataForExistingPublisher';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $result = $example->render($publisher_id);
				echo "<pre>";print_r($result);echo "</pre>";exit;
			    $this->adsensehostauth->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	
	
	function verify_token($token){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
				
			    $this->adsensehostauth->authenticate('adgeek');
			  	$action = 'VerifyAssociationSession';
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $result = $example->render($token);
			    printHtmlFooter();
				$this->adsensehostauth->refreshToken();
				if($result['status'] == 'REJECTED'){
					redirect('account/create_failed');
				}
				elseif($result['status'] == 'ACCEPTED'){ // publisher accepted the association
					$content = $this->get_all_ad_clients_for_publisher($result['accountId']);
					$user_data = $this->session->userdata('user_data');
					$content['websiteUrl'] = $user_data['websiteUrl'];
					
					$this->publisher->insert_info($content);
					redirect('account/register_success');
				}
				else{
					echo $result['status'];
				}
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function create(){
			try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			$sessionData = $this->input->post(NULL, TRUE);
			
			try {
				//echo "<pre>";print_r($this->session->userdata('user_data'));echo "</pre>";
			  	//echo "<pre>";print_r($sessionData);echo "</pre>";exit;
			  	//$this->adsensehostauth->setRedirectUri('http://'.$_SERVER['HTTP_HOST'].'/account/create');
			   	$this->adsensehostauth->authenticate('adgeek');
			  
			  	$action = 'StartAssociationSession';
			    
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    $result = $example->render($sessionData);
				//echo "<pre>";print_r($result);echo "</pre>";exit
				$this->adsensehostauth->refreshToken();
				
				header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function getSupportedActions() {
			  $actions = array();
			  $dirHandler = opendir(LIB_DOC_ROOT.'/examples');
			  while ($actionFile = readdir($dirHandler)) {
			    if (preg_match('/\.php$/', $actionFile)) {
			      $action = preg_replace('/\.php$/', '', $actionFile);
			      $actions[] = $action;
			    }
			  }
			  closedir($dirHandler);
			  asort($actions);
			  return $actions;
	}
	
	function showMyErrors($client) {
	  // print the soap
	  //showRequestResponse($client);
	  var_dump($client->detail);
	  echo"<pre>";print_r($client->detail);echo "</pre>";
	
	  // print the error information
	  echo '<h2>Fault Code</h2>' . "\n";
	  echo "<b>Fault:</b>  {$client->fault}<br>\n";
	  echo "<b>Code:</b> {$client->faultcode}<br>\n";
	  echo "<b>String:</b> {$client->faultstring}<br>\n";
	  echo "<b>Detail:</b> {$client->faultdetail}<br>\n";
	}
	
	function toHtml($text)
	{
	  $my_text = htmlspecialchars($text, ENT_QUOTES);
	  $remove = array ("&lt;", " xmlns");
	  $insert = array ("<br>&lt;", "<br>    xmlns");
	  $my_text = str_replace($remove, $insert, $my_text);
	  return $my_text;
	}
	
	function associate_validation(){
		//echo "<pre>";print_r($this->input->post(NULL, TRUE));echo "</pre>";exit;
		$this->form_validation->set_rules('accountExist', 'Account Exist', 'trim|xss_clean');
		$this->form_validation->set_rules('loginEmail', 'Login Email', 'trim|required|valid_email|xss_clean');
		$this->form_validation->set_rules('postalCode', '郵政編碼', 'min_length[3]||max_length[5]|trim|required|is_natural|xss_clean');
		$this->form_validation->set_rules('phone', '電話末5碼', 'min_length[5]||max_length[5]|trim|number|required|is_natural|xss_clean');
		//$this->form_validation->set_rules('developerUrl', 'Developer URL', 'trim|required|xss_clean');
		$this->form_validation->set_rules('emailPromotionPreferences', 'Email Promotions Preferences', 'trim|required|xss_clean');
		$this->form_validation->set_rules('adsenseGuidelineRule1', 'Account Exist', 'trim|xss_clean');
		$this->form_validation->set_rules('adsenseGuidelineRule2', 'Account Exist', 'trim|xss_clean');
		
		if($this->form_validation->run()){
			$this->session->set_userdata('user_data',$this->input->post(NULL, TRUE));
			redirect('account/register_form_confirm');
		}
		else{
			$this->load->view('adsense/register_form', '');
		}
	}

	function associate(){
		$associate_data = $this->input->post(NULL, TRUE);
		//echo "<pre>";print_r($associate_data);echo "</pre>";
		
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>NOT RELEVANT</client_id>";
		if($this->config->item('debug_association_type', 'adsense') == 'Active'){
			$debug_association_type = "<debug_association_type>Active</debug_association_type>";
			$header = $email . $password . $client_id . $debug_association_type;
		}
		else{
			$header = $email . $password . $client_id ;
		}
		
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl,TRUE);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		
		// setting the parameter
		$param = "<loginEmail>".$associate_data['loginEmail']."</loginEmail>";
		$param .= "<postalCode>".$associate_data['postalCode']."</postalCode>";
		$param .= "<phone>".$associate_data['phone']."</phone>";
		$param .= "<developerUrl>".$this->config->item('developer_url', 'adsense')."</developerUrl>";
		$param = "<ns1:associateAccount xmlns:ns1=\"$namespace\">" . $param . "</ns1:associateAccount>";

		
		// invoke web service
		$response = $client->call('associateAccount', $param, $namespace);
		//echo "<pre>";print_r($response);echo "</pre>";exit;
		if(empty($client->detail)){ //create success
			$associate_data['developerUrl'] = $this->config->item('developer_url', 'adsense');
		
			if(isset($response['return']['id'])){ // only one product
				$associate_data['googleID_'.$response['return']['type']['value']] = $response['return']['id'];
				$associate_data['accountExist'] = 'true';	
			}
			else{//for multi products: content ads & search ads
				foreach($response['return'] as $key=>$val){
					$associate_data['googleID_'.$val['type']['value']] = $val['id'];	
				}
				$associate_data['accountExist'] = 'true';
			}
				
			$this->publisher->insert_info($associate_data);// record publisher register info
			
			redirect('/account/register_success');
		}
		else{
			redirect('/account/register_form/'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']);
		}
	}
}

/* End of file account.php */
/* Location: ./application/controllers/account.php */
